package com.lerning.edu.manage.controller;

import com.lerning.edu.commons.util.DateUtil;
import com.lerning.edu.services.CampusDSRService;
import com.lerning.edu.services.RevenueService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiangwei
 * @since 18/7/5
 */
@Component
@EnableScheduling
public class LockDSRRevenueController {
    private static Logger log = LoggerFactory.getLogger(LockDSRRevenueController.class);


    @Autowired
    private RevenueService revenueService;
    @Autowired
    private CampusDSRService campusDSRService;

    /***
     * Revenue月度KPI达成
     * 每周一凌晨0点30分执行(周一报表)
     */
    @Scheduled(cron = "0 30 0 ? * MON")
    public void dsrByCampusKpiForFRI() {
        //获取前一天年月日
        String lastDate = DateUtil.getLastDateStr1() + " 23:59:59";

        //获取前三天的时间
        String lastTheDate = DateUtil.getLastDateStrN(3) + " 23:59:59";

        //跨财务月时计算数据锁定日期
        Map dqd = new HashMap();
        dqd.put("dqDay", lastTheDate.subSequence(0, 7));
        List FinanceMonthOfDq = campusDSRService.queryNatureMonthOfDq(dqd);//当前月

        Map dateMap = (HashMap) FinanceMonthOfDq.get(0);

        Map dqd1 = new HashMap();
        dqd1.put("dqDay", lastDate.subSequence(0, 7));
        List FinanceMonthOfDq1 = campusDSRService.queryNatureMonthOfDq(dqd1);//当前月
        Map dateMap1 = (HashMap) FinanceMonthOfDq1.get(0);

//        //财务月的后一个周五跟财务月最后一天在同一个月,则锁定下个财务月的数据
        if (DateUtil.compare_date(dateMap1.get("EndDate").toString(), lastTheDate)) {
            dateMap.put("dqDay", DateUtil.addMonth(lastTheDate).substring(0,7));
            FinanceMonthOfDq = campusDSRService.queryNatureMonthOfDq(dateMap);//当前月
            dateMap = (HashMap) FinanceMonthOfDq.get(0);
        }

        if (!DateUtil.compare_date(dateMap.get("EndDate").toString(), lastDate)) {
            lastDate = dateMap.get("EndDate").toString();
        }
        //跨财务月时计算数据锁定日期

        String beninDate = dateMap.get("BeginDate").toString();

        Map map = new HashMap();
        map.put("startTime", beninDate);
        map.put("endTime", lastDate);
        map.put("nowYear", lastDate.substring(0, 4));
        map.put("nowMonth", lastDate.substring(5, 7));
        map.put("text", lastDate.substring(0, 10));

        List revenues = revenueService.queryRevenueByWeek(map);

        if (revenues.size() > 0) {
            revenueService.insertRevenues(revenues);
            log.info("Revenue月度KPI达成  锁定成功");
        }
    }
}
